package task_list_tab

import (
	"file_explorer/service/task"
	"file_explorer/view/components/main_panel/fe_tab"
	"file_explorer/view/packed_widgets"
	"file_explorer/view/store"

	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/theme"
	"fyne.io/fyne/v2/widget"
)

type TaskListTab struct {
	fe_tab.DefaultTab

	taskList *widget.List

	tabCtx *store.TaskListTabContext
}

func newTaskItem() fyne.CanvasObject {
	buttons := widget.NewToolbar()
	layer := container.NewBorder(nil, nil, packed_widgets.NewLabel(""), buttons)
	var startButton *packed_widgets.Toggle
	startButton = packed_widgets.NewToggle("", "", theme.MediaPauseIcon(), theme.MediaPlayIcon())
	buttons.Append(startButton)
	buttons.Append(packed_widgets.NewButton("", theme.CancelIcon(), nil))
	return container.NewVBox(
		layer,
		widget.NewProgressBar(),
		widget.NewSeparator(),
	)
}

func NewTaskListTab(tabCtx store.TabContext) *TaskListTab {
	var tab *TaskListTab
	tab = &TaskListTab{
		tabCtx: tabCtx.(*store.TaskListTabContext),
		taskList: widget.NewList(
			func() int {
				return tabCtx.GetGlobalContext().TaskManager.GlobalTaskLength()
			},
			func() fyne.CanvasObject {
				return newTaskItem()
			},
			func(id widget.ListItemID, object fyne.CanvasObject) {
				tsk := tabCtx.GetGlobalContext().TaskManager.GetGlobalTask(id)
				label := object.(*fyne.Container).Objects[0].(*fyne.Container).Objects[0].(*packed_widgets.Label)
				label.SetText(tsk.GetLabel())

				buttons := object.(*fyne.Container).Objects[0].(*fyne.Container).Objects[1].(*widget.Toolbar)
				runningToggle := buttons.Items[0].(*packed_widgets.Toggle)
				cancelButton := buttons.Items[1].(*packed_widgets.Button)
				if runningToggle.OnSwitch == nil {
					runningToggle.OnSwitch = func(running bool) {
						if running {
							tsk.Continue()
							return
						}
						tsk.Pause()
					}
				}
				if cancelButton.OnTapped == nil {
					cancelButton.OnTapped = func() {
						tabCtx.GetGlobalContext().TaskManager.DeleteGlobalTask(tsk)
					}
				}

				progressBar := object.(*fyne.Container).Objects[1].(*widget.ProgressBar)
				progressBar.TextFormatter = func() string {
					return tsk.GetProgress()
				}
				progressBar.SetValue(tsk.GetPercentage())
				progressBar.Refresh()
			},
		),
	}

	tab.Container = container.NewBorder(nil, nil, nil, nil, tab.taskList)

	// 定期刷新任务
	tabCtx.GetGlobalContext().TaskManager.SubmitTabTask(tab.tabCtx.GetTabItem(),
		task.NewPollTask(50, func() {
			tab.taskList.Refresh()
		}),
	)

	return tab
}
